package vn.com.aptech.msh.controller;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.constraints.Min;
import vn.com.aptech.msh.business.IUserBean;
import vn.com.aptech.msh.entities.User;
import vn.com.aptech.msh.utils.NavigationHelper;
import vn.com.aptech.msh.utils.ResourceBundleHelper;

/**
 *
 * @author trietto
 */
@Named("registerController")
@RequestScoped
public class RegisterController implements Serializable {

    @Inject
    IUserBean userBusiness;
    User model;
    @Min(3)
    private int roleId = 3;

    @PostConstruct
    public void init() {
        model = new User();
    }

    public void validateUsernameExists(FacesContext context, UIComponent toValidate, Object value)
            throws ValidatorException {
        String tUsername = (String) value;
        if (userBusiness.isUsernameExists(tUsername)) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, ResourceBundleHelper.get("validator.register.usernameExists"), "");
            throw new ValidatorException(message);
        }
    }

    public void validateEmailExists(FacesContext context, UIComponent toValidate, Object value)
            throws ValidatorException {
        String tEmail = (String) value;
        if (userBusiness.isEmailExist(tEmail)) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, ResourceBundleHelper.get("validator.register.emailExists"), "");
            throw new ValidatorException(message);
        }
    }

    public String register() {
        try {
            userBusiness.registerUser(model, roleId);
            return NavigationHelper.toSuccessPage("register");
        } catch (Exception ex) {
            Logger.getLogger(RegisterController.class.getName()).log(Level.SEVERE, null, ex);
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, ResourceBundleHelper.get("register.failed"), "");
            FacesContext.getCurrentInstance().addMessage("frmRegister", msg);
            return null;
        }
    }

    public User getModel() {
        return model;
    }

    public void setModel(User model) {
        this.model = model;
    }

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }
}
